<template>
  <div class="insurance-process-container">
    <h1>智能保险全流程处理</h1>
    
    <!-- 表单区域 -->
    <div class="form-section">
      <el-form 
        :model="formData" 
        :rules="formRules" 
        ref="insuranceForm" 
        label-width="120px"
        label-position="top"
        @submit.prevent="handleSubmit"
      >
        <h2>投保人信息</h2>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="投保人姓名" prop="aname">
              <el-input v-model="formData.aname" placeholder="请输入投保人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投保人身份证号" prop="acard_id">
              <el-input 
                v-model="formData.acard_id" 
                placeholder="请输入18位身份证号" 
                maxlength="18"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入11位手机号" maxlength="11" />
        </el-form-item>

        <h2>被保人信息</h2>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="被保人姓名" prop="bname">
              <el-input v-model="formData.bname" placeholder="请输入被保人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="被保人身份证号" prop="bcard_id">
              <el-input 
                v-model="formData.bcard_id" 
                placeholder="请输入18位身份证号" 
                maxlength="18"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="与投保人关系" prop="relationship">
          <el-select v-model="formData.relationship" placeholder="请选择关系">
            <el-option label="本人" value="本人" />
            <el-option label="配偶" value="配偶" />
            <el-option label="子女" value="子女" />
            <el-option label="父母" value="父母" />
          </el-select>
        </el-form-item>

        <h2>保险信息</h2>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="保单生效日期" prop="effective_date">
              <el-date-picker
                v-model="formData.effective_date"
                type="date"
                placeholder="选择日期"
                :disabled-date="disabledDate"
                value-format="YYYY-MM-DD"
              />
              <div class="form-tip">默认7天后生效，最长不超过30天</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保险期限(年)" prop="term_years">
              <el-input-number 
                v-model="formData.term_years" 
                :min="1" 
                :max="10" 
                controls-position="right"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmit"
            :loading="isSubmitting"
          >
            提交申请
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 提交成功提示 -->
    <div v-if="submissionSuccess" class="submission-success">
      <el-alert type="success" :closable="false" center>
        <template #title>
          <h3>申请已成功提交！</h3>
          <p>系统正在处理您的保险申请，请10分钟后再来查看结果。</p>
          <p>任务ID: {{ taskId }}</p>
          <el-button 
            type="primary" 
            @click="checkStatus"
            :loading="isCheckingStatus"
          >
            立即查看状态
          </el-button>
        </template>
      </el-alert>
    </div>

    <!-- 结果展示区域 -->
    <div class="result-section" v-if="resultData">
      <h2>处理结果</h2>
      
      <div v-if="resultData.status === 'success'" class="success-result">
        <el-alert type="success" :closable="false">
          <template #title>
            <h3>保险申请已通过</h3>
          </template>
          <p>合同编号: {{ resultData.data.contract_id }}</p>
        </el-alert>

        <el-card class="result-card">
          <template #header>
            <div class="card-header">
              <span>合同详情</span>
            </div>
          </template>
          <div class="contract-content">
            <pre>{{ JSON.stringify(resultData.data.review_result, null, 2) }}</pre>
          </div>
        </el-card>
      </div>

      <div v-else-if="resultData.status === 'review_failed'" class="failed-result">
        <el-alert type="error" :closable="false">
          <template #title>
            <h3>保险申请未通过</h3>
          </template>
          <p>{{ resultData.message }}</p>
        </el-alert>

        <el-card class="result-card">
          <template #header>
            <div class="card-header">
              <span>审核详情</span>
            </div>
          </template>
          <div class="review-details">
            <p>{{ resultData.details }}</p>

            <div v-if="resultData.suggestions.length > 0" class="suggestions">
              <h4>改进建议:</h4>
              <ul>
                <li v-for="(suggestion, index) in resultData.suggestions" :key="index">
                  {{ suggestion }}
                </li>
              </ul>
            </div>
          </div>
        </el-card>
      </div>

      <div v-else-if="resultData.status === 'processing'" class="processing-result">
        <el-alert type="info" :closable="false">
          <template #title>
            <h3>申请正在处理中</h3>
          </template>
          <p>您的保险申请仍在处理中，请稍后再来查看结果。</p>
          <p>任务ID: {{ taskId }}</p>
        </el-alert>
      </div>

      <div v-else-if="resultData.status === 'error'" class="error-result">
        <el-alert type="warning" :closable="false">
          <template #title>
            <h3>处理流程异常</h3>
          </template>
          <p>{{ resultData.message }}</p>
        </el-alert>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-overlay">
      <el-spinner size="large" />
      <p>正在提交您的保险申请...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'


import { useRoute,useRouter } from 'vue-router';

const route = useRoute();
const orderId = route.query.orderId; // 获取orderId参数
const router = useRouter(); // 获取 router 实例



// 表单数据
const formData = reactive({
  aname: '',
  bname: '',
  acard_id: '',
  bcard_id: '',
  phone: '',
  relationship: '本人',
  effective_date: '',
  term_years: 1
})

// 表单验证规则
const formRules = reactive({
  aname: [{ required: true, message: '请输入投保人姓名', trigger: 'blur' }],
  bname: [{ required: true, message: '请输入被保人姓名', trigger: 'blur' }],
  acard_id: [
    { required: true, message: '请输入投保人身份证号', trigger: 'blur' },
    { len: 18, message: '身份证号必须为18位', trigger: 'blur' }
  ],
  bcard_id: [
    { required: true, message: '请输入被保人身份证号', trigger: 'blur' },
    { len: 18, message: '身份证号必须为18位', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { len: 11, message: '手机号必须为11位', trigger: 'blur' }
  ],
  relationship: [{ required: true, message: '请选择关系', trigger: 'change' }]
})

// 结果数据
const resultData = ref(null)
const isSubmitting = ref(false)
const isLoading = ref(false)
const isCheckingStatus = ref(false)
const submissionSuccess = ref(false)
const taskId = ref('')
const insuranceForm = ref(null)

// 禁用过去的日期和超过30天的日期
const disabledDate = (time) => {
  const today = new Date()
  const maxDate = new Date()
  maxDate.setDate(today.getDate() + 30)
  return time.getTime() < today.setHours(0, 0, 0, 0) || time.getTime() > maxDate.getTime()
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 验证表单
    await insuranceForm.value.validate()
    isSubmitting.value = true
    isLoading.value = true
    
    // 设置默认生效日期（7天后）
    const effectiveDate = formData.effective_date || getDefaultEffectiveDate()
    
    // 准备提交数据
    const submitData = {
      ...formData,
      effective_date: effectiveDate, // 添加默认生效日期
      order_id:orderId,  // 添加订单ID
    }

    // 调用API
    const response = await axios.post('http://127.0.0.1:8000/ai/insuranceprocess/', submitData)
    
    // 处理响应
    taskId.value = response.data.task_id
    submissionSuccess.value = true
    ElMessage.success('申请已提交，请稍后查看结果')
    
  } catch (error) {
    console.error('提交失败:', error)
    if (error.response) {
      resultData.value = error.response.data
    } else {
      ElMessage.error('请求失败: ' + error.message)
    }
  } finally {
    isSubmitting.value = false
    isLoading.value = false
  }
}


// 检查任务状态
const checkStatus = async () => {
  try {
    isCheckingStatus.value = true
    const response = await axios.get(`http://127.0.0.1:8000/ai/insurance/status/${taskId.value}/`)
    resultData.value = response.data
    addStatus()

    if (response.data.status === 'processing') {
      ElMessage.info('申请仍在处理中，请稍后再试')
    } else {
      submissionSuccess.value = false
      // 添加10秒后跳转逻辑
      setTimeout(() => {
        router.push('/'); // 跳转到首页
      }, 5000); // 10秒 = 10000毫秒
    }
  } catch (error) {
    console.error('检查状态失败:', error)
    ElMessage.error('检查状态失败: ' + error.message)
  } finally {
    isCheckingStatus.value = false
  }
}

// 添加合同到数据库
const addStatus = async () => {
    const response = await axios.get(`http://127.0.0.1:8000/ai/addstatus/`,{params: {userid:localStorage.getItem('user_id'),
        text:resultData.value.details,contract_id:orderId}})
}

// 获取默认生效日期（7天后）
const getDefaultEffectiveDate = () => {
  const date = new Date()
  date.setDate(date.getDate() + 7)
  return formatDate(date)
}

// 格式化日期为YYYY-MM-DD
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 重置表单
const resetForm = () => {
  insuranceForm.value.resetFields()
  resultData.value = null
  submissionSuccess.value = false
  taskId.value = ''
}
</script>

<style scoped>
.insurance-process-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.form-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

h2 {
  margin: 20px 0 15px;
  color: #666;
  font-size: 18px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.result-section {
  margin-top: 30px;
}

.result-card {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
}

.contract-content {
  background: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  max-height: 500px;
  overflow-y: auto;
}

.suggestions {
  margin-top: 15px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
}

.suggestions h4 {
  margin-bottom: 10px;
}

.suggestions ul {
  margin: 0;
  padding-left: 20px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-overlay p {
  margin-top: 15px;
  font-size: 16px;
}

.submission-success {
  margin: 20px 0;
}

.submission-success h3 {
  margin-bottom: 10px;
}

.submission-success p {
  margin: 5px 0;
}

.processing-result {
  margin-top: 20px;
}
</style>